package com.example.Activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.example.Utils.FileHelper;
import com.example.training.R;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class FileListActivity extends Activity
        implements AdapterView.OnItemClickListener {

    private  ListView _list_files;
    private String _path;
    private ArrayList<HashMap<String, Object>> _items;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.filelist_activity);
        _list_files = (ListView)findViewById(R.id.list_include_files);
        _list_files.setOnItemClickListener(this);
        _path = getIntent().getStringExtra("path");
        LoadFiles();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int index, long l){
        String path = CombineFileName((String)_items.get(index).get("name"));
        File file =new File(path);
        if(file.isDirectory()){
            _path = path;
            LoadFiles();
        }else{
            Intent intent = new Intent(this, FileDetailActivity.class);
            intent.putExtra("path", path);
            startActivity(intent);
        }
    }

    public void Upward(View view){
        if(_path.equals("/")){
            return;
        }
        File file =new File(_path);
        _path = file.getParent();
        LoadFiles();
    }

    private void LoadFiles(){
        List<String> rets =  FileHelper.EnumFiles(_path);

        _items = new ArrayList<HashMap<String, Object>>();
        for(String name: rets){
            HashMap<String, Object> item = new HashMap<String, Object>();
            item.put("name", name);
            File file =new File(CombineFileName(name));
            if(file.isDirectory()){
                item.put("image", R.drawable.folder32);
            }
            else{
                item.put("image", R.drawable.file32);
            }
            _items.add(item);
        }
        _list_files.setAdapter(new SimpleAdapter(this, _items,
                R.layout.filelist_liststyle,
                new String[]{"name", "image"},
                new int[]{R.id.filelist_liststyle_content, R.id.filelist_liststyle_icon})
        );
        TextView _text_path = (TextView)findViewById(R.id.text_full_path);
        _text_path.setText(_path);
    }

    private String CombineFileName(String name){
        if(_path.endsWith("/")){
            return File.separator + name;
        }else{
            return _path + File.separator + name;
        }
    }

}
